from dash.dependencies import Input, Output, State
from dash import html, dcc
from models import User
from server import server
from flask import session # 确保导入 session
from models import User # 确保导入 User 模型
from dash import html, dcc, Input, Output, State # 确保导入 Dash 组件

def register_callbacks(app):
    """
    注册登录模块的回调函数
    """
    @app.callback(
        # 将 Output ID 从 "redirect-target" 改回 "redirect-admin"
        Output("redirect-admin", "pathname"), # 使用布局中实际存在的 ID
        Output("login-output", "children"),
        [Input("login-button", "n_clicks")],
        [State("username-input", "value"), State("password-input", "value")],
        prevent_initial_call=True
    )
    def process_login(n_clicks, username, password):
        if not username or not password:
            return None, html.Div("请输入用户名和密码", className="text-danger")

        user = User.query.filter_by(username=username, is_active=True).first()

        if user and user.check_password(password):
            # 登录成功后设置session
            session['user_id'] = user.id
            # 存储角色信息到 session，方便后续使用（可选）
            session['user_role'] = user.role

            # 优先跳转到扫码前保存的 after_login 页面
            after_login = session.pop('after_login', None)
            # print(f"p35 after_login: {after_login}")
            if after_login:
                # 自动补全前缀
                if not after_login.startswith('/dash/'):
                    after_login = '/dash' + after_login if after_login.startswith('/') else '/dash/' + after_login
                    # print(f"p39 after_login: {after_login}")
                return after_login, ""

            
            pathname = "/dash/bigscreen"  # 普通用户跳转到大屏页面
           

            # 返回重定向路径和空消息
            return pathname, ""
        else:
            # 返回 None 表示不改变 pathname, 返回错误信息
            return None, html.Div("用户名或密码错误", className="text-danger")
